<?php

/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

class Application_Model_ArticleMapper extends Ahs_Model_Mapper
{

    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->DbTableName = 'Application_Model_DbTable_Articles';
        $this->PropertiesMap = array
        (
            "Id"            => "article_id",
            "AuthorId"      => "article_author_id",
            "ChapterId"     => "article_chapter_id",
            "Name"          => "article_name",
            "Text"          => "article_text",
            "CreationDate"  => "article_creationdate",
            "ModifiedDate"  => "article_modifieddate",
            "DeletedDate"   => "article_deleteddate",
        );
    }
    
    /**
     * Get all articles
     * 
     * @return Array(Application_Model_Article)
     */
    public function fetchAll()
    {        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(''.$this->getColumn('DeletedDate').' IS NULL');
        $rows = $table->fetchAll($select);
        return $this->_toArticles($rows);
    }

    /**
     * Get an article by its ID
     * 
     * @param integer $id
     * @return Application_Model_Article
     */
    public function fetchById($id)
    {
        $row = $this->getDbTable()->fetchRow(array(''.$this->getColumn('Id').' = ?' => $id));
        return $this->_toArticle($row);
    }
    
    /**
     * Search article by name
     * 
     * @param string $name
     * @return Array(Application_Model_Article) 
     */
    public function fetchByName($name)
    {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(
                    ''.$this->getColumn('Name').' LIKE :name'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
               ->bind( array(':name' => "%{$name}%") )
               ->order(''.$this->getColumn('Name').' ASC')
               ->limit(10);
        $rows = $table->fetchAll($select);
        return $this->_toArticles($rows);
    }
    
    /**
     * Get all articles by name for an author
     * 
     * @return Array(Application_Model_Article)
     */
    public function fetchByNameAndAuthorId($article_name, $author_id)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->where(
                    ''.$this->getColumn('Name').'  LIKE :name'                    
                       . ' AND ' .
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':name' => "%{$article_name}%", ':id' => $author_id))
               ->order(''.$this->getColumn('Name').' ASC');
        $rows = $table->fetchAll($select);
        return $this->_toArticles($rows);
    }
    
    /**
     * Search article by chapter id
     * 
     * @param integer $chapter_id
     * @return Array(Application_Model_Article) 
     */
    public function fetchByChapterId($chapter_id)
    {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(
                    ''.$this->getColumn('ChapterId').' = :chapter_id'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
               ->bind( array(':chapter_id' => $chapter_id) )
               ->order(''.$this->getColumn('Name').' ASC');
        $rows = $table->fetchAll($select);
        return $this->_toArticles($rows);
    }
    
     /**
     * Get all articles for an author
     * 
     * @param integer $author_id
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To disable paging, 
     *                              pass null as value (default) and return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_Chapter)
     */
    public function fetchByAuthorId($author_id, $page_nr=null, $nr_results=10)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->where(
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':id' => $author_id))
               ->order(''.$this->getColumn('CreationDate').' DESC');
        
        if($page_nr != null && $page_nr > 0)
            $select->limitPage($page_nr, $nr_results);
        
        $rows = $table->fetchAll($select);
        return $this->_toArticles($rows);
    }
    
    /**
     * Get the total number of books
     * 
     * @return integer
     */
    public function getCount()
    {
        $ids    = array();
        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array('count(*) as count'));
        $select->where(''.$this->getColumn('DeletedDate').' IS NULL');
        
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    /**
     * Get the total number of articles for this author
     * 
     * @param integer $author_id
     * @return integer
     */
    public function getCountByAuthorId($author_id)
    {
        $ids    = array();        
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->from($table, array('count(*) as count'));
        $select->where(
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':id' => $author_id));
        $rows = $table->fetchAll($select);        
        
        return $rows[0]->count;
    }
    
    
    /**
     * Save an article
     *
     * @param Application_Model_Article $article
     */
    public function save(Application_Model_Article $article)
    {
        $article_id = $article->Id;
        
        $data = $this->_getTableValues($article, array("Id"));
        $data[$this->getColumn("ModifiedDate")] = new Zend_Db_Expr('NOW()');
        
        if(null == $article_id)
        {
            // Set some default values
            $data[$this->getColumn("CreationDate")] = new Zend_Db_Expr('NOW()');
            $data[$this->getColumn("AuthorId")]     = $this->getLoggedInUserId();
        
            $article_id = $this->getDbTable()->insert($data);
        }
        else
        {
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $article_id));
        }
        
        return $article_id;
    }
    
    /**
     * Delete an article by id
     *
     * @param integer $id
     */
    public function delete($id)
    {   
        if (null != $id)
        {
            $data[$this->getColumn('DeletedDate')] = new Zend_Db_Expr('NOW()');
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $id));
        }
    }
    
    /**
     * Undelete an article by id
     *
     * @param integer $id
     */
    public function undelete($id)
    {   
        if (null != $id)
        {
            $data[$this->getColumn('DeletedDate')] = new Zend_Db_Expr('NULL');
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $id));
        }
    }
    
    /**
     * Convert a row to object
     * 
     * @param Zend_Db_Table_Row_Abstract $row
     * @return Application_Model_Article
     */
    private function _toArticle(Zend_Db_Table_Row_Abstract $row = null)
    {
        // Create our object
        $object = new Application_Model_Article();
        
        // Only go on if we actually have a row
        if($row)
        {
            // We have a propertiesmap, let's try to map it back to an object
            foreach($this->PropertiesMap as $key=>$column)
            {
                if(isset($row[$column]))
                    $object->$key      = $row[$column];
            }
        }

        return $object;
    }

    /**
     * Convert a rowset to an array of objects
     * 
     * @param Zend_Db_Table_Rowset_Abstract $rows
     * @return Array(Application_Model_Article)
     */
    private function _toArticles(Zend_Db_Table_Rowset_Abstract $rows = null)
    {
        $results = array();
        if ($rows)
        {
            foreach ($rows as $row)
            {
                $results[] = $this->_toArticle($row);
            }
        }
        return $results;
    }
}


